<template>
    <view>
        <!-- marketing/pages/timeCoupon/timeCoupon.wxml -->
        <view>
            <view class="is_time stickyClass" v-if="isTime">
                <view
                    @tap="titleClick"
                    :data-idx="index"
                    :data-time_status="item.status"
                    :class="index == currentIndex ? 'item_tag_click' : 'item_tag'"
                    v-for="(item, index) in timeList"
                    :key="index"
                >
                    <view class="time_tag">
                        {{ item.startHourStr }}
                    </view>

                    <view class="state_tag">
                        <text v-if="item.status == 1">即将开始</text>
                        <text v-if="item.status == 2">抢购中</text>
                        <text v-if="item.status == 3">已结束</text>
                    </view>
                </view>
            </view>

            <view class="hd_box">
                <view class="hd_time" v-if="isTime && currentTimeStatus != 3">
                    <view class="time_tit" v-if="currentTimeStatus == 1">距离本场开始</view>
                    <view class="time_tit" v-if="currentTimeStatus == 2">距离本场结束</view>

                    <view class="time_text" v-if="currentTimeStatus != 3">
                        <view class="text_tag">{{ hour }}</view>
                        :
                        <view class="text_tag">{{ minu }}</view>
                        :
                        <view class="text_tag">{{ sec }}</view>
                    </view>
                </view>
                <view class="hd_des" @tap="hdDes">活动说明</view>
            </view>

            <!-- 活动时间段券信息 -->
            <view class="swiper_box">
                <view class="item_tag" v-for="(item, index) in couponList" :key="index">
                    <view class="item_box">
                        <!-- wx:if="{{item.status != 2}}" -->
                        <view class="item_li">
                            <image class="item_bg" v-if="item.status != 4" src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/line_bg.png" />
                            <image class="item_bg" v-if="item.status == 4" src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/line_bg2.png" />
                            <view class="item_content">
                                <view class="item_fl">
                                    <image
                                        v-if="item.status == 2 || item.status == 3"
                                        class="fl_label"
                                        src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/label.png"
                                    />
                                    <image v-if="item.status == 4" class="fl_label" src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/label2.png" />
                                    <view class="fl_jine">
                                        <text class="jine_fl">￥</text>
                                        <text class="jine_fr">{{ item.balance / 100 }}</text>
                                    </view>
                                </view>
                                <view class="item_fr">
                                    <view class="fr_line1">
                                        <view class="title">
                                            <text>{{ item.typeName }}</text>
                                        </view>
                                        <view class="shiyong" @tap="goShiyong" v-if="item.status == 2 || item.status == 3">去使用</view>
                                    </view>
                                    <view class="fr_line2">
                                        <view class="des">满{{ item.limitBalance / 100 }}可用</view>
                                    </view>
                                    <view class="fr_line3">
                                        <view class="kucun" v-if="item.status != 4">
                                            <view class="bgs" :style="'width:' + item.percentage * 100 + '%'"></view>
                                            <view class="txt">当前库存{{ item.inventory }}</view>
                                        </view>
                                        <view
                                            class="qiang"
                                            @tap="goQiang"
                                            :data-coupon_id="item.id"
                                            :data-time_id="item.timeId"
                                            :data-activity_id="item.activityId"
                                            v-if="item.status == 1 || item.status == 2"
                                        >
                                            马上抢
                                        </view>
                                    </view>
                                    <view class="fr_line4">
                                        <view class="date">有效期: {{ activityDetail.freeValidPeriodStr }} - {{ activityDetail.rewardValidPeriodStr }}</view>

                                        <!-- <view class="date">
                                    始: {{activityDetail.freeValidPeriod}}
                                </view>
                                <view class="date">
                                    止: {{activityDetail.rewardValidPeriod}}
                                </view> -->
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 活动说明弹出框 -->
        <u-popup :show="ruleVisible" @close="onClose" confirmButtonText="" customStyle="width:95%" :round="20" mode='center'>
            <view class="rule_box">
                <view class="rule_title">
                    <view class="rule_txt">
                        <text>活动说明</text>
                    </view>
                    <image class="rule_icon" src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/close.png" mode="" @tap="unHdDes" />
                </view>
                <view class="rule_date">
                    <view class="title">活动期限：</view>
                    <view class="content">
                        <text>{{ activityDetail.fromDate }}</text>
                        <text>~ {{ activityDetail.deadDate }}</text>
                    </view>
                </view>

                <view class="rule_des">
                    <view class="title">活动说明：</view>
                    <view class="content">
                        {{ activityDetail.remark }}
                    </view>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
// 'use strict';
// import vanDialog from './@vant/weapp/dialog/index';

// exports.__esModule = true; // marketing/pages/timeCoupon/timeCoupon.ts

var timeCouponApi_1 = require('../../../api/timeCouponApi');

var util_1 = require('../../../utils/util');

export default {
    components: {
        // vanDialog
    },
    data() {
        return {
            currentTimeStatus: null,
            currentIndex: 0,

            activityDetail: {
                freeValidPeriodStr: '',
                rewardValidPeriodStr: '',
                fromDate: '',
                deadDate: '',
                remark: ''
            },

            timeList: [],
            couponList: [],
            timer: null,
            isTime: false,
            ruleVisible: false,

            couponTypeEnum: [
                {
                    value: 'FuWuFei',
                    name: '服务券'
                },
                {
                    value: 'DianFei',
                    name: '电费券'
                },
                {
                    value: 'XianJin',
                    name: '现金券'
                }
            ],

            activityId: '',
            hour: '',
            minu: '',
            sec: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options);

        if (options.activityId) {
            this.setData({
                activityId: options.activityId
            });
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getActivityIds(this.activityId);
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        console.log('onHide....'); //关闭clearInterval定时函数

        clearInterval(this.timer);
        this.setData({
            timer: null
        });
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // console.log('onUnload.....')
        //关闭clearInterval定时函数
        clearInterval(this.timer);
        this.setData({
            timer: null
        });
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    // onPullDownRefresh() {
    //     this.getActivityIds(this.data.activityId)
    // },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        uni.stopPullDownRefresh();
        var that = this;
        setTimeout(function () {
            // 这里写刷新要调用的函数，比如：
            that.getActivityIds(that.activityId);
        }, 500);
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        //去使用按钮
        goShiyong: function () {
            uni.switchTab({
                url: '../../../pages/index/index'
            });
        },

        //马上抢按钮
        goQiang: function (e) {
            var that = this; // console.log(e.currentTarget.dataset)

            var couponId = e.currentTarget.dataset.coupon_id;
            var timeId = e.currentTarget.dataset.time_id;
            var activityId = e.currentTarget.dataset.activity_id; // console.log(activityId,'活动id......')
            // status 券状态 枚举
            // 1. 当优惠券仍然有库存，用户未领取，且用户满足领取条件时 优惠券显示（显示抢券按钮）
            // 2. 当优惠券仍然有库存，用户已领取，且能继续领取时，优惠券显示为【已抢到】（显示抢券按钮）
            // 3. 当优惠券仍然有库存，用户已领取，且不能继续领取时，优惠券显示为【已抢到】（删除抢券按钮）
            // 4. 当优惠券没有库存时，显示为已抢完 （删除抢券按钮）
            // 5. 当活动时间还没开始时（删除抢券按钮）

            timeCouponApi_1
                .getInventoryRob({
                    couponId: couponId,
                    timeId: timeId,
                    activityId: activityId
                })
                .then(function (res) {
                    // console.log(res.data)
                    if (res.code == 0) {
                        uni.showToast({
                            title: '抢券成功，请前往个人中心查看',
                            icon: 'none',
                            duration: 2000
                        });
                        that.getActivityIds(that.activityId);
                    } else {
                        uni.showToast({
                            title: '抢券失败',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                });
        },

        //点击tab时触发
        titleClick: function (e) {
            // console.log(e.currentTarget.dataset.idx)
            // console.log(e.currentTarget.dataset.time_status,'sssssssssssss')
            this.setData({
                //拿到当前索引并动态改变
                currentIndex: e.currentTarget.dataset.idx,
                currentTimeStatus: e.currentTarget.dataset.time_status
            });
            this.restTime(); //点击时间段重新给券列表赋值

            this.getCouponList(this.timeList[e.currentTarget.dataset.idx].couponList); // console.log(this.data.timeList, '活动的时间对象')
            // console.log(this.data.couponList, '活动的优惠券对象')
        },

        getCouponList: function (datas) {
            //浅拷贝coupon
            var coupon = datas;
            coupon.forEach(function (item, index) {
                if (item.type == 'FuWuFei') {
                    item.typeName = '服务券';
                } else if (item.type == 'DianFei') {
                    item.typeName = '电费券';
                } else if (item.type == 'XianJin') {
                    item.typeName = '现金券';
                }

                item.percentage = item.inventory / item.count;
            });
            this.setData({
                couponList: coupon
            }); // console.log('当前券列表',coupon)
        },

        //活动说明打开关闭
        hdDes: function () {
            // console.log('打开活动说明;;;')
            this.setData({
                ruleVisible: true
            });
        },

        unHdDes: function () {
            // console.log('关闭活动说明;;;')
            this.setData({
                ruleVisible: false
            });
        },

        // 获取活动倒计时
        restTime: function () {
            // console.log(this.data.currentIndex,'currentIndex*****')
            var timeDate = util_1.formatTime(new Date()).split(' ')[0]; // console.log(timeDate,'获取当前日期时间')

            var dateEnd = this.timeList[this.currentIndex].endHourStr; // console.log(dateEnd)

            var dateStart = this.timeList[this.currentIndex].startHourStr; // console.log(dateStart)

            var dateTime = null;

            if (this.currentTimeStatus == 2) {
                dateTime = timeDate + ' ' + dateEnd;
            } else if (this.currentTimeStatus == 1) {
                dateTime = timeDate + ' ' + dateStart;
            } // console.log(this.data.timeList,'timeList------------')
            // console.log(dateTime,'dateTime------------')

            var setTime = new Date(dateTime); // var setTime = new Date("2022/11/15 20:00:00")

            var nowTime = new Date();
            var restSec = setTime.getTime() - nowTime.getTime(); // 时分秒计算

            var hour = Math.floor((restSec / (60 * 60 * 1000)) % 24);
            var minu = Math.floor((restSec / (60 * 1000)) % 60);
            var sec = Math.floor((restSec / 1000) % 60); // console.log(hour,minu,sec)
            //进行补0操作

            if (hour < 10) {
                hour = '0' + hour;
            } else {
                hour = hour;
            }

            if (minu < 10) {
                minu = '0' + minu;
            } else {
                minu = minu;
            }

            if (sec < 10) {
                sec = '0' + sec;
            } else {
                sec = sec;
            } // var str = hour+":"+minu+":"+sec
            // console.log(str)

            this.setData({
                hour: hour,
                minu: minu,
                sec: sec
            }); // console.log(this.data.hour)
        },

        //获取活动id
        getActivityIds: function (activityId) {
            var that = this;
            timeCouponApi_1.getActivityId(activityId).then(function (res) {
                console.log(res.data);
                uni.showNavigationBarLoading(); //在标题栏中显示加载图标

                if (res.code == 0) {
                    uni.hideNavigationBarLoading(); //在标题栏中隐藏加载图标

                    if (res.data.activity) {
                        console.log('开始时间', res.data.activity.freeValidPeriod);
                        console.log('结束时间', res.data.activity.rewardValidPeriod);
                        res.data.activity.freeValidPeriodStr = res.data.activity.freeValidPeriod.split(' ')[0];
                        res.data.activity.rewardValidPeriodStr = res.data.activity.rewardValidPeriod.split(' ')[0];
                        that.setData({
                            activityDetail: res.data.activity
                        });
                    } // 全天  根据 couponList 有没有时段

                    if (res.data.couponList) {
                        that.setData({
                            timeList: res.data.couponList,
                            couponList: res.data.couponList
                        });
                    } else {
                        // 时间段
                        that.setData({
                            timeList: res.data.timeList,
                            couponList: res.data.timeList[that.currentIndex].couponList
                        });
                    } //默认券列表赋值

                    that.getCouponList(that.couponList); // console.log(this.data.activityDetail, '活动信息')
                    // console.log(this.data.timeList, '活动的时间对象')
                    // console.log(this.data.couponList, '活动的优惠券对象')

                    var that_1 = that;

                    if (res.data.timeList) {
                        // console.log('有时间段!!!!')
                        // 获取活动倒计时
                        that_1.timer = setInterval(function () {
                            that_1.restTime();
                        }, 1000);
                        that_1.setData({
                            timer: that_1.timer,
                            isTime: true,
                            currentTimeStatus: res.data.timeList[0].status
                        });
                    } else {
                        // console.log('无时间段')
                        that_1.setData({
                            timer: null,
                            isTime: false
                        });
                    }
                } else {
                    uni.hideNavigationBarLoading(); //在标题栏中隐藏加载图标

                    uni.showToast({
                        title: res.msg,
                        icon: 'none',
                        duration: 2000
                    });
                }
            });
        },

        onClose() {
            console.log('占位：函数 onClose 未声明');
        }
    }
};
</script>
<style lang="less" scoped>
/* marketing/pages/timeCoupon/timeCoupon.wxss */
page {
    background-color: #f5f7fa;
}

.stickyClass {
    position: sticky; /*吸顶定位*/
    top: 0;
    z-index: 999;
}

.is_time {
    width: 100%;
    height: 112rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;
    .item_tag {
        text-align: center;
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #606266;
    }
    .item_tag_click {
        text-align: center;
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #00b680;
    }
}

.hd_box {
    padding: 39rpx 24rpx;
    display: flex;
    justify-content: space-between;
    .hd_time {
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #303133;
        display: flex;
        .time_tit {
            margin-right: 16rpx;
        }
        .time_text {
            display: flex;
            .text_tag {
                text-align: center;
                /* width: 40rpx;*/
                /* height: 40rpx;*/
                background: rgb(155, 155, 155, 0.5);
                border-radius: 5rpx;
                color: #fff;
                margin: 0 8rpx;
                padding: 0 5rpx;
            }
        }
    }
    .hd_des {
        font-size: 24rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #00b680;
    }
}

.swiper_box {
    /* background: pink;*/
    padding: 0 24rpx;
    padding-bottom: 46rpx;
    .item_tag {
        .item_box {
            height: 224rpx;
            margin-bottom: 16rpx;
            .item_li {
                width: 100%;
                height: 224rpx;
                margin: 0;
                padding: 0;
                position: relative;
                .item_bg {
                    position: absolute;
                    width: 100%;
                    height: 224rpx;
                }
                .item_content {
                    position: absolute;
                    z-index: 1;
                    display: flex;
                    width: 100%;
                    height: 100%;
                    .item_fl {
                        width: 230rpx;
                        position: relative;
                        .fl_label {
                            position: absolute;
                            top: 0;
                            left: 0;
                            width: 107rpx;
                            height: 110rpx;
                        }
                        .fl_jine {
                            margin-top: 33%;
                            text-align: center;
                            color: #ffffff;
                            opacity: 0.8;
                            font-family: PingFang SC;
                            font-weight: bold;
                            .jine_fl {
                                font-size: 34rpx;
                            }
                            .jine_fr {
                                font-size: 60rpx;
                            }
                        }
                    }
                    .item_fr {
                        width: 60%;
                        padding: 0 32rpx;
                        .fr_line1 {
                            margin-top: 16rpx;
                            display: flex;
                            justify-content: space-between;
                            .title {
                                font-size: 34rpx;
                                font-family: PingFang SC;
                                font-weight: bold;
                                color: #303133;
                            }
                            .shiyong {
                                width: 104rpx;
                                height: 32rpx;
                                border: 1rpx solid #00b680;
                                border-radius: 4rpx;
                                text-align: center;
                                font-size: 20rpx;
                                font-family: PingFang SC;
                                font-weight: 500;
                                color: #00b680;
                            }
                        }
                        .fr_line2 {
                            margin-top: 12rpx;
                            .des {
                                font-size: 26rpx;
                                font-family: PingFang SC;
                                font-weight: 500;
                                color: #606266;
                            }
                        }
                        .fr_line3 {
                            margin-top: 16rpx;
                            display: flex;
                            justify-content: space-between;
                            .kucun {
                                width: 260rpx;
                                height: 32rpx;
                                background: #ffa569;
                                border-radius: 4rpx;
                                position: relative;
                                .bgs {
                                    background: #fa7035;
                                    border-radius: 4rpx;
                                    position: absolute;
                                    height: 100%;
                                }
                                .txt {
                                    position: absolute;
                                    left: 28%;
                                    font-size: 20rpx;
                                    font-family: PingFang SC;
                                    font-weight: 500;
                                    color: #ffffff;
                                }
                            }
                            .qiang {
                                text-align: center;
                                width: 104rpx;
                                height: 32rpx;
                                background: #00b680;
                                border-radius: 16rpx;
                                font-size: 20rpx;
                                font-family: PingFang SC;
                                font-weight: 500;
                                color: #ffffff;
                            }
                        }
                        .fr_line4 {
                            margin-top: 16rpx;
                            .date {
                                font-size: 24rpx;
                                font-family: PingFang SC;
                                font-weight: 500;
                                color: #909399;
                            }
                        }
                    }
                }
            }
        }
    }
}

.rule_box {
    padding: 45rpx 32rpx;
    .rule_title {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        .rule_txt {
            width: 92%;
            text-align: center;
            > text {
                font-size: 34rpx;
                font-family: PingFang SC;
                font-weight: bold;
                color: #303133;
            }
        }
        .rule_icon {
            width: 27rpx;
            height: 27rpx;
        }
    }
    .rule_date {
        font-size: 30rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #606266;
        margin-top: 32rpx;
        .title {
            font-size: 32rpx;
        }
    }
    .rule_des {
        font-size: 30rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #606266;
        margin-top: 32rpx;
        .title {
            font-size: 32rpx;
        }
    }
}
</style>
